package org.itboys.fuzion.service;

import javax.annotation.Resource;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.itboys.framework.resource.ResourceHolder;
import org.itboys.fuzion.dto.FuzionMemberRedisDto;
import org.itboys.fuzion.entity.FuzionMember;
import org.itboys.fuzion.entity.MemberTwoCodeMedia;
import org.itboys.fuzion.tools.HttpUrlUtils;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseService;
import org.itboys.weixin.service.WeixinTwoCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 会员的二维码相关
 * @author weisky
 *
 * 2016年4月18日
 */
@Service
public class MemberTwoCodeService extends BaseService<MemberTwoCodeMedia, Long>{

	private static final long serialVersionUID = 1L;
	
	@Autowired
	private ResourceHolder resourceHolder;
	@Autowired
	private WeixinTwoCodeService weixinTwoCodeService;
	@Autowired
	private MemberTwoCodeMediaService memberTwoCodeMediaService;
	@Autowired
	private FuzionMemberService fuzionMemberService;
	
	@Resource(name="baseMongoDS")
	private MongoDataSource ds;

	@Override
	protected MongoDataSource getMongoDataSource() {
		return ds;
	}
	
	/**
	 * 将生成的二维码存在自己的服务器上
	 * @param memberId
	 * @return
	 */
	public String createMemberTwoCodeSaveSer(Long memberId){

		/*MemberTwoCodeMedia mmm = memberTwoCodeMediaService.getByField("memberId", memberId);
		if(mmm != null && StringUtils.isNotBlank(mmm.getTwocodeUrl())){//如果已经保存过  就直接返回
			logger.info("二维码查询成功：MemberTwoCodeMedia:"+ JSON.toJSONString(mmm));
			return mmm.getTwocodeUrl();
		}*/

		FuzionMember fm = fm = fuzionMemberService.getById(memberId);
		if(fm != null){
			if(fm.getReaded()){
				if(fm != null){
					String twoCodeUrl = weixinTwoCodeService.createSceneTwoCode(Long.parseLong(fm.getWeixinId()), memberId);
					String saveTitle = resourceHolder.getStringValue("fileUploadPath");
					String saveUrl = "/twocode/"+fm.getSellerId()+ "_" +memberId+".png";//自己服务器上保存图片的路径
					boolean result = HttpUrlUtils.buildImg(saveTitle+saveUrl, twoCodeUrl);//将生成的二维码存在自己的服务器上
					if(result){
						List<MemberTwoCodeMedia> mmm = memberTwoCodeMediaService.findByField("memberId", memberId);
						if(mmm != null){
							MemberTwoCodeMedia mtm = new MemberTwoCodeMedia();
							mtm.setMemberId(memberId);
							mtm.setSellerId(fm.getSellerId());
							mtm.setTwocodeUrl(saveUrl);
							memberTwoCodeMediaService.save(mtm);//将二维码保存到数据库
							logger.info("生成并保存二维码成功：MemberTwoCodeMedia:"+ JSON.toJSONString(mtm));
						}
					}
					return saveUrl;//返回保存的地址
				}
			}
		}
		return null;
	}

}
